<!-- 支付页面 -->
<template>
	<view :style="mix_diyStyle">
  <view class="container">
    <view class="order_info flex_column_start_start">
      <view class="item b_b flex_row_between_center">
        <text class="tit">{{ $L('订单编号') }}</text>
        <text class="order_sn">{{ paySn }}</text>
      </view>
      <view class="item flex_row_between_center">
        <text class="tit">{{ $L('订单金额') }}</text>
        <view class="order_amount">
          <text class="unit">{{ $L('￥') }}</text>
          <text class="price_int">{{ $getPartNumber(needPay, 'int') }}</text>
          <text class="price_decimal">{{
            $getPartNumber(needPay, 'decimal')
          }}</text>
        </view>
      </view>
    </view>
    <view class="pay_part flex_column_start_start">
      <text class="title">{{ $L('选择支付方式') }}</text>
      <view
        v-for="(item, index) in payMethod"
        :key="index"
        @click="selectPayMethod(item)"
        :class="{
          item: true,
          b_b: index < payMethod.length - 1,
          flex_row_between_center: true
        }"
      >
        <view class="left flex_row_start_center">
          <image class="pay_icon" :src="item.payIcon" />
          <text class="tit">{{ item.payMethodName }}</text>
        </view>
        <view class="right">
          <text
            class="balance_available"
            v-if="item.payMethod == 'balance'"
            :class="{
              active: filters.toNum(balanceAva) >= filters.toNum(needPay)
            }"
            >{{
              $L('余额：￥') +
              $getPartNumber(balanceAva, 'int') +
              $getPartNumber(balanceAva, 'decimal')
            }}</text
          >
          <text
            :class="{
              iconfont: true,
              iconziyuan33: selData.payMethod == item.payMethod,
              iconziyuan43: selData.payMethod != item.payMethod,
              has_sel: selData.payMethod == item.payMethod
            }"
          ></text>
        </view>
      </view>
    </view>
    <!-- 余额支付支付密码 start -->
    <view class="balance_password" v-if="balanceCon">
      <view class="balance_password_title">{{ $L('支付密码') }}</view>
      <view class="input_password">
        <view class="input_password_con">
          <input
            type="password"
            v-model="passwordVal"
            :placeholder="$L('请输入支付密码')"
            @blur="passwordBlur"
            v-if="!isShowPasw"
          />
          <input
            type="text"
            v-model="passwordVal"
            :placeholder="$L('请输入支付密码')"
            @blur="passwordBlur"
            v-else
          />
          <text
            :class="{
              iconfont: true,
              iconziyuan81: isShowPasw,
              iconziyuan9: !isShowPasw
            }"
            @click="showPasword"
          ></text>
        </view>
      </view>
    </view>
    <!-- 余额支付支付密码 end -->
    <view
      v-if="payMethod.length"
      class="btn_recharge flex_row_center_center"
      :style="{ top: windowHeight - 60 + 'px' }"
      @click="pay"
      >{{ $L('立即支付') }}</view
    >
  </view>
	</view>
</template>
<!-- '@vue/cli-plugin-babel/preset' -->
<script>
import { mapState } from 'vuex'
import filters from '@/utils/filter.js'
export default {
  data() {
    return {
      paySn: '', //支付单号
      payInfo: {}, //订单信息
      selData: {},
      payMethod: [], //支付方式
      client: 'wxbrowser', //支付发起来源 pc==pc,mbrowser==移动设备浏览器,app==app,wxxcx==微信小程序,wxbrowser==微信内部浏览器
      payMethodType: 'create', //从哪里进入支付，create 下单，orderList 订单列表 orderDetail 订单详情 recharge 充值
      isAllowAutoPay: true, //当浏览器地址有code时，是否允许自动支付，如果支付失败的话置为false
      autoPayInterval: '', //定时器
      wxBrowerCode: '', //微信浏览器支付的code
      balanceCon: false, //输入余额支付密码的框是否显示
      passwordVal: '', //密码值
      isShowPasw: false, //支付密码是否可见
      hasSetPassword: false, //用户是否已经设置了余额支付支付密码
      oriUrl: '', //不带code的页面地址
      windowHeight: '',
      ifOnShow: false,
      needPay: 0,
      balanceAva: 0,
      filters
    }
  },
  computed: {
    ...mapState(['hasLogin', 'userInfo'])
  },
  onHide() {
    this.ifOnShow = true
  },
  onShow() {
    if (this.ifOnShow) {
      this.isSetPassword()
    }
  },
  // #ifdef H5
  onBackPress() {
    if (this.$isWeiXinBrower()) {
      if (window.history.length > 3) {
        window.history.go(-2)
      } else {
        window.history.back()
      }
      return true
    }
  },
  // #endif
  onLoad(option) {
    setTimeout(()=>{
      uni.setNavigationBarTitle({
        title: this.$L('收银台')
      })
    },0);
    
    this.initClient()
    this.paySn = this.$Route.query.paySn

    //#ifdef H5
    //判断code地址的参数 start
    let cur_code = this.$getQueryVariable('code')
    if (cur_code) {
      uni.showLoading({
        title: this.$L('支付中...'),
        mask: true
      })
      let oriUrl = this.$Route.query.ori_url + 'extra/tshou/tsGift/giftPay'
      this.oriUrl = oriUrl
      if (this.client == 'wxbrowser') {
        //微信浏览器的话要把浏览器地址里面的code去掉
        history.replaceState({}, '', this.oriUrl)
      }
      this.wxBrowerCode = cur_code
    }
    //判断code地址的参数 end
    //#endif

    this.payMethodType =
      option.payMethodType != undefined
        ? option.payMethodType
        : this.payMethodType
    this.getGitPay()
    this.getPayMethod()
    this.isSetPassword()
    uni.getSystemInfo({
      success: (res) => {
        this.windowHeight = res.windowHeight
      }
    })
  },
  onUnload() {
    if (this.autoPayInterval) {
      clearInterval(this.autoPayInterval)
    }
  },
  methods: {
    //初始化终端类型
    initClient() {
      //#ifdef APP-PLUS
      this.client = 'app'
      //#endif
      //#ifdef H5
      this.client = this.$isWeiXinBrower() ? 'wxbrowser' : 'mbrowser'
      //#endif
      //#ifdef MP-WEIXIN
      this.client = 'wxxcx'
      //#endif
    },
    getGitPay() {
      this.$request({
        url: 'v3/spreader/front/spreader/pay/buyGiftBag',
        method: 'POST'
      }).then((res) => {
        if (res.state == 200) {
          this.paySn = res.data.paySn
          this.needPay = res.data.needPay
          this.balanceAva = res.data.balanceAvailable
        } else {
          this.$api.msg(res.msg)
        }
      })
    },

    //获取支付方式
    getPayMethod() {
      let { client, payMethodType, wxBrowerCode } = this
      this.$request({
        url: 'v3/business/front/orderPay/payMethod',
        data: {
          source: client,
          type: 1
        }
      })
        .then((res) => {
          if (res.state == 200) {
            res.data.map((item) => {
              item.payIcon =
                getApp().globalData.imgUrl +
                `pay/${item.payMethod}_pay_icon.png`
            })
            this.payMethod = res.data
            if (!this.payMethod.length) {
              return
            }
            if (!wxBrowerCode) {
              this.selData = this.payMethod[0]
            } else {
              //有code的话要默认选中微信支付，并直接提交订单
              this.selData = this.payMethod.filter(
                (item) => item.payMethod == 'wx'
              )[0]
              let _this = this
              if (this.isAllowAutoPay) {
                this.autoPayInterval = setInterval(function () {
                  if (_this.needPay != undefined) {
                    _this.pay()
                    //清除倒计时
                    clearInterval(_this.autoPayInterval)
                  }
                }, 1000)
              }
            }
          }
        })
        .catch((e) => {})
    },
    //选择支付方式事件
    selectPayMethod(val) {
      let _this = this
      if (val.payMethod == 'balance') {
        //余额支付
        if (this.hasSetPassword) {
          if (Number(this.balanceAva) < Number(this.needPay)) {
            //余额小于订单金额
            uni.showToast({
              title: _this.$L('您的余额不足,请选择其他支付方式！'),
              icon: 'none'
            })
          } else {
            this.balanceCon = true
            this.selData = val
          }
        } else {
          uni.showModal({
            title: _this.$L('温馨提示!'),
            content: _this.$L('未设置支付密码'),
            confirmColor: '#FC1E1C',
            confirmText: _this.$L('立即设置'),
            cancelText: _this.$L('取消'),
            success: function (res) {
              if (res.confirm) {
                _this.$Router.push({
                  path: '/pages/account/managePwd',
                  query: { source: 'set_pay' }
                })
              } else if (res.cancel) {
              }
            }
          })
        }
      } else {
        this.selData = val
        this.balanceCon = false
      }
    },
    //余额支付是否已设置过密码
    isSetPassword() {
      this.$request({
        url: 'v3/business/front/orderPay/payPwdCheck',
        method: 'GET'
      })
        .then((res) => {
          if (res.state == 200) {
            this.hasSetPassword = res.data
          }
        })
        .catch((e) => {})
    },

    //失焦,获取输入密码值
    passwordBlur(e) {
      this.passwordVal = e.detail.value
      var reg = /^[\w.]{6,20}$/
      //密码的验证 6～20位，英文、数字或符号
      let flag = reg.test(this.passwordVal)
      if (!flag) {
        uni.showToast({
          title: this.$L('请输入6~20位英文、数字或符号'),
          icon: 'none',
          duration: 1000
        })
        this.passwordVal = ''
      }
    },
    //密码是否可见
    showPasword() {
      this.isShowPasw = !this.isShowPasw
    },
    //立即支付事件
    pay() {
      const { selData, client, wxBrowerCode } = this
      let _this = this
      let param = {}
      param.url = 'v3/spreader/front/spreader/pay/doPay'
      param.method = 'POST'
      param.data = {}
      param.data.payType = selData.payType
      param.data.payMethod = selData.payMethod
      param.data.paySn = this.paySn
      if (selData.payMethod == 'balance') {
        //余额支付
        param.data.payPwd = this.$base64Encrypt(this.passwordVal) //支付密码,使用余额时必传
      } else {
        if (client == 'wxxcx') {
          //微信小程序支付
          uni.login({
            success: (code) => {
              param.data.code = code.code
              param.data.codeSource = 1 //用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器
              this.$request(param)
                .then((res) => {
                  if (res.state == 200) {
                    let tmp_data = res.data.payData
                    if (res.data.actionType == null) {
                      //微信小程序支付
                      uni.requestPayment({
                        timeStamp: tmp_data.timeStamp,
                        nonceStr: tmp_data.nonceStr,
                        package: tmp_data.packageValue,
                        signType: 'MD5',
                        paySign: tmp_data.paySign,
                        success: function (res) {
                          _this.payTip('success')
                        },
                        fail: function (res) {
                          _this.payTip('fail')
                        }
                      })
                    }
                  } else {
                    _this.$api.msg(res.msg)
                  }
                })
                .catch((e) => {})
            }
          })
          return false
        } else if (client == 'wxbrowser') {
          //微信h5支付
          if (!wxBrowerCode) {
            let tar_url = location.href
            tar_url += location.href.indexOf('?') > -1 ? '&' : '?'
            tar_url += 'ori_url=' + location.href
            let uricode = encodeURIComponent(tar_url)
            window.location.href =
              'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
              getApp().globalData.h5AppId +
              '&redirect_uri=' +
              uricode +
              '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
            return false
          } else {
            param.data.code = wxBrowerCode
            param.data.codeSource = 2 //用户code来源（JSAPI支付时必填）：1==小程序，2==微信内部浏览器
          }
        }
      }

      this.$request(param)
        .then((res) => {
          if (res.state == 200) {
            if (selData.payMethod == 'balance') {
              uni.showToast({
                title: this.$L('支付成功!'),
                duration: 700
              })
              setTimeout(() => {
                this.$Router.replace('/extra/tshou/user/user')
              }, 1000)
            } else {
              let tmp_data = res.data.payData
              if (res.data.actionType == 'redirect') {
                window.location.href = tmp_data
              } else if (res.data.actionType == null) {
                if (client == 'wxbrowser') {
                  uni.hideLoading()
                  this.wxBrowerCode = ''
                  //微信h5支付
                  this.$weiXinBrowerPay({
                    timestamp: tmp_data.timeStamp,
                    nonceStr: tmp_data.nonceStr,
                    package: tmp_data.packageValue,
                    signType: 'MD5',
                    paySign: tmp_data.paySign,
                    appId: tmp_data.appId, //此参数可不用
                    success: function (r) {
                      if (r.errMsg == 'chooseWXPay:ok') {
                        _this.payTip('success')
                      } else {
                        _this.payTip('fail')
                        _this.isAllowAutoPay = false //支付失败后禁止自动支付
                      }
                    },
                    cancel: function (r) {
                      _this.payTip('fail')
                      _this.isAllowAutoPay = false //支付失败后禁止自动支付
                    }
                  })
                } else if (client == 'wxxcx') {
                  //微信小程序支付
                  uni.requestPayment({
                    timeStamp: tmp_data.timeStamp,
                    nonceStr: tmp_data.nonceStr,
                    package: tmp_data.packageValue,
                    signType: 'MD5',
                    paySign: tmp_data.paySign,
                    success: function (res) {
                      _this.payTip('success')
                    },
                    fail: function (res) {
                      _this.payTip('fail')
                    }
                  })
                } else if (client == 'app') {
                  //APP支付
                  let provider = ''
                  let orderInfo = {}
                  if (selData.payMethod == 'wx') {
                    provider = 'wxpay'
                    orderInfo.appid = tmp_data.appId
                    orderInfo.noncestr = tmp_data.nonceStr
                    orderInfo.package = tmp_data.packageValue
                    orderInfo.partnerid = tmp_data.partnerId
                    orderInfo.prepayid = tmp_data.prepayId
                    orderInfo.timestamp = tmp_data.timeStamp
                    orderInfo.sign = tmp_data.sign
                  } else if (selData.payMethod == 'alipay') {
                    provider = 'alipay'
                  }
                  uni.requestPayment({
                    provider: provider,
                    orderInfo:
                      provider == 'alipay' ? res.data.payData : orderInfo, //订单数据
                    success: function (res) {
                      _this.payTip('success')
                    },
                    fail: function (err) {
                      _this.payTip('fail')
                    }
                  })
                }
              } else if (res.data.actionType == 'autopost') {
                document.write(res.data.payData)
              }
            }
          } else {
            this.$api.msg(res.msg)
            if (this.passwordVal != '') {
              this.passwordVal = ''
            }
          }
        })
        .catch((e) => {})
    },

    //支付操作完成提示
    payTip(type) {
      //如果来自下单，直接跳转订单列表，否则返回上一级页面（订单列表或者订单详情），并更新数据
      if (type == 'success') {
        //提示支付成功
        uni.showToast({
          title: this.$L('支付成功!'),
          duration: 700
        })
        setTimeout(() => {
          this.$Router.replace('/extra/tshou/user/user')
        }, 1000)
      } else if (type == 'fail') {
        //提示支付失败
        this.$api.msg(this.$L('支付失败,请重试～'))
      }
      this.toBeTs()
    }
  }
}
</script>

<style lang="scss">
page {
  background: #ffffff;
  width: 750rpx;
  margin: 0 auto;
}

.container {
  display: flex;
  flex-direction: column;
  flex: 1;

  .order_info {
    border-top: 20rpx solid #f5f5f5;
    width: 750rpx;
    background: #fff;

    .item {
      position: relative;
      height: 100rpx;
      width: 100%;
      padding: 0 20rpx;

      .tit {
        color: $main-font-color;
        font-size: 30rpx;
      }

      .order_sn {
        color: #2d2d2d;
        font-size: 26rpx;
      }

      &.b_b:after {
        left: 20rpx;
      }

      .order_amount {
        color:var(--color_extral_main);
        font-weight: bold;

        .unit,
        .price_decimal {
          font-size: 24rpx;
          margin-right: 3rpx;
          line-height: 24rpx;
        }

        .price_int {
          font-size: 34rpx;
          line-height: 34rpx;
        }
      }
    }
  }

  .pay_part {
    border-top: 20rpx solid #f5f5f5;
    background: #fff;
    flex: 1;

    .title {
      color: $main-font-color;
      font-size: 32rpx;
      margin-top: 30rpx;
      margin-left: 20rpx;
    }

    .item {
      width: 100%;
      padding: 20rpx;
      position: relative;

      .left {
        .pay_icon {
          width: 80rpx;
          height: 80rpx;
        }

        .tit {
          color: $main-font-color;
          font-size: 28rpx;
          margin-left: 20rpx;
        }
      }

      .right {
        .balance_available {
          font-size: 28rpx;
          color: #999;
          margin-right: 20rpx;
        }

        .active {
          color: var(--color_extral_main);
        }

        .iconfont {
          color: $main-third-color;
          font-size: 32rpx;
        }

        .has_sel {
          color: var(--color_extral_main);
        }

        &.b_b:after {
          left: 20rpx;
        }
      }
    }
  }

  .balance_password {
    border-top: 20rpx solid #f5f5f5;

    .balance_password_title {
      width: 750rpx;
      height: 100rpx;
      display: flex;
      align-items: center;
      font-size: 30rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 39rpx;
      padding-left: 20rpx;
      box-sizing: border-box;
      border-bottom: 1rpx solid #f5f5f5;
      background: #ffffff;
    }

    .input_password {
      width: 750rpx;
      height: 86rpx;
      background: #ffffff;

      .input_password_con {
        margin: 0 41rpx;
        height: 86rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid #f5f5f5;

        input {
          font-size: 26rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #999999;
          line-height: 39rpx;
        }

        text {
          color: #666666;
          font-size: 20rpx;
        }
      }
    }
  }

  .btn_recharge {
    width: 670rpx;
    height: 88rpx;
    background:var(--color_extral_main);
    border-radius: 44rpx;
    color: #fff;
    font-size: 36rpx;
    position: absolute;
    right: 0rpx;
    left: 0rpx;
    margin: 0 auto;
  }
}
</style>
